package com.example.socialmediaplatform.post;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

import com.example.socialmediaplatform.model.Notification;
import com.example.socialmediaplatform.model.NotificationRepository;
import com.example.socialmediaplatform.controller.NotificationWebSocketController;

@RestController
@RequestMapping("/api/post")
public class PostInteractionController {
    @Autowired
    private PostJpaRepository postJpaRepository;
    @Autowired
    private PostLikeRepository postLikeRepository;
    @Autowired
    private NotificationRepository notificationRepository;
    @Autowired
    private NotificationWebSocketController notificationWebSocketController;

    // 评论某帖
    @PostMapping("/{postId}/comment")
    public ResponseEntity<?> addComment(Authentication authentication, @PathVariable Long postId, @RequestBody PostCommentDTO dto) {
        Optional<Post> postOpt = postJpaRepository.findById(postId);
        if (postOpt.isEmpty()) return ResponseEntity.notFound().build();
        Post post = postOpt.get();
        PostComment comment = new PostComment(authentication.getName(), dto.getContent(), dto.getCreateTime() == null ? new Date() : dto.getCreateTime());
        post.getComments().add(comment);
        postJpaRepository.save(post);
        // 通知帖子作?
        if (!authentication.getName().equals(post.getUsername())) {
            Notification n = new Notification();
            n.setType("comment");
            n.setContent(authentication.getName() + " 评论了你的帖? " + dto.getContent());
            n.setFromUser(authentication.getName());
            n.setToUser(post.getUsername());
            n.setReaded(false);
            n.setCreatedAt(new Date());
            notificationRepository.save(n);
            notificationWebSocketController.sendNotificationToUser(post.getUsername(), n);
        }
        return ResponseEntity.ok("评论成功");
    }

    // 获取某帖所有评�?
    @GetMapping("/{postId}/comments")
    public ResponseEntity<?> getComments(@PathVariable Long postId) {
        Optional<Post> postOpt = postJpaRepository.findById(postId);
        if (postOpt.isEmpty()) return ResponseEntity.notFound().build();
        List<PostComment> comments = postOpt.get().getComments();
        return ResponseEntity.ok(comments);
    }

    // 点赞某帖
    @PostMapping("/{postId}/like")
    public ResponseEntity<?> likePost(Authentication authentication, @PathVariable Long postId) {
        String username = authentication.getName();
        List<PostLike> exists = postLikeRepository.findByPostIdAndUsername(postId, username);
        if (!exists.isEmpty()) return ResponseEntity.badRequest().body("已点赞");
        PostLike like = new PostLike();
        like.setPostId(postId);
        like.setUsername(username);
        postLikeRepository.save(like);
        // 通知帖子作�?
        Optional<Post> postOpt = postJpaRepository.findById(postId);
        if (postOpt.isPresent() && !username.equals(postOpt.get().getUsername())) {
            Notification n = new Notification();
            n.setType("like");
            n.setContent(username + " 点赞了你的帖子");
            n.setFromUser(username);
            n.setToUser(postOpt.get().getUsername());
            n.setReaded(false);
            n.setCreatedAt(new Date());
            notificationRepository.save(n);
            notificationWebSocketController.sendNotificationToUser(postOpt.get().getUsername(), n);
        }
        return ResponseEntity.ok("点赞成功");
    }

    // 取消点赞
    @DeleteMapping("/{postId}/like")
    @Transactional
    public ResponseEntity<?> unlikePost(Authentication authentication, @PathVariable Long postId) {
        String username = authentication.getName();
        postLikeRepository.deleteByPostIdAndUsername(postId, username);
        return ResponseEntity.ok("已取消点赞");
    }

    // 获取某帖点赞数和用户
    @GetMapping("/{postId}/likes")
    public ResponseEntity<?> getLikes(@PathVariable Long postId) {
        List<PostLike> likes = postLikeRepository.findByPostId(postId);
        List<String> users = likes.stream().map(PostLike::getUsername).collect(Collectors.toList());
        return ResponseEntity.ok(new LikeInfo(likes.size(), users));
    }

    public static class LikeInfo {
        public int count;
        public List<String> users;
        public LikeInfo(int count, List<String> users) {
            this.count = count;
            this.users = users;
        }
    }
} 
